package com.itheima.springboottilasmanager.InterCeper;

import com.itheima.springboottilasmanager.util.ApplicationContext;
import com.itheima.springboottilasmanager.util.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
@Component
@Slf4j
public class LoginInterCeper implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        2.判断路径是否是登录路径
        String token  = request.getHeader("token");
//        如果是登录路径，则放行
        if(token==null){
            log.info("Interceptor登录请求，没有令牌");
            //执行登录请求
            response.setStatus(401);
            return false;//注意登录后，会回到过滤器，执行过滤后的操作
        }
        //        如果不是登录路径，则获取令牌
//        如果携带了,则进行解析
        //        如果解析失败直接封装401
        try {
            Claims claims = JwtUtils.parseJWT(token);
            JwtUtils.parseJWT(token);
            Integer id = (Integer) claims.get("id");
            ApplicationContext.setEmpId(id);
        } catch (Exception e) {
            log.info("Interceptor令牌解析失败，返回401");
            response.setStatus(401);
            return  false;
        }
        log.info("Interceptor令牌解析成功，放行");
        return true;
    }
}
